<script setup>
import {useCartStore} from '@/stores/cartStore';
import {useRouter} from 'vue-router';
import {updateCart} from "@/apis/cart";
import {ElMessage} from "element-plus";

const router = useRouter();
const cartStore = useCartStore();

// 单选回调
const singleCheck = (i, selected) => {
  // 修改 pinia 中 selected
  if (i.count === 0){
    ElMessage.warning("数量为0！不可结算")
  }else {
    cartStore.singleCheck(i.id, selected);
  }
}

// 全选回调
const allCheck = (seller,selected) => {
  console.log(seller)
  cartStore.allCheck(seller,selected);
}

// 删除购物车商品
const delCart = async (i) => {
  await cartStore.delCart(i.id);
  ElMessage.success("删除【" + i.name + "】成功！");
}

// 下单结算
const handleCheckout = async () => {
  const sellers = new Set(); // 使用 Set 数据结构来存储卖家信息
  for (const item of cartStore.cartList) {
    if (item.selected) { // 判断商品是否被选中
      sellers.add(item.goodsCreateBy);
    }
  }
  if (sellers.size <= 0 || sellers.size > 1) {
    const warningMessage = sellers.size <= 0 ? '请选择需要结算的商品！' : '您选中结算的商品来自不同的卖家，请分开下单';
    ElMessage.warning(warningMessage);
  } else {
    let hasCheckout = true;
    for (const item of cartStore.cartList) {
      if (item.selected && item.count > item.goodsStock) {
        hasCheckout = false;
        ElMessage.warning('商品【'+ item.name +'】的结算数量大于库存，无法结算！');
        break
      }
    }
    if (hasCheckout) {
      // 否则，更新购物车并跳转至结算页面
      await updateCart(cartStore.cartList);
      await router.push('/checkout');
    }
  }
}

console.log(cartStore.sellers)
</script>

<template>
  <div class="xtx-cart-page">
    <div class="container m-top-20">
      <div class="cart">
        <table>
          <thead>
          <tr>
            <th width="120">卖家</th>
            <th width="400">商品信息</th>
            <th width="220">单价</th>
            <th width="180">数量</th>
            <th width="180">小计</th>
            <th width="140">操作</th>
          </tr>
          </thead>
          <!-- 商品列表 -->
          <tbody>
          <!-- 使用 v-for 循环渲染购物车列表中的商品 -->
          <template v-for="(seller, sellerIndex) in cartStore.sellers" :key="'seller-' + sellerIndex">
            <tr>
              <!-- 显示卖家名称 -->
              <td colspan="6">
                <el-checkbox :model-value="seller.checked" @change="(checked) => allCheck(seller, checked)">{{ seller.name }}</el-checkbox>
              </td>
            </tr>
            <!-- 渲染该卖家的商品列表 -->
            <tr v-for="item in seller.items" :key="item.id">
              <!-- 商品信息 -->
              <td>
                <!-- 单选框 -->
                <el-checkbox :model-value="item.selected" @change="(selected) => singleCheck(item, selected)"/>
              </td>
              <td>
                <div class="goods">
                  <RouterLink :to="'/detail/' + item.goodsId "><img :src="item.picture" alt=""/></RouterLink>
                  <div>
                    <p class="name ellipsis">
                      {{ item.name }}
                    </p>
                  </div>
                </div>
              </td>
              <td class="tc">
                <p>&yen;{{ item.price }}</p>
              </td>
              <td class="tc">
                <el-input-number :min="1" v-model="item.count"/>
              </td>
              <td class="tc">
                <p class="f16 red">&yen;{{ (item.price * item.count).toFixed(2) }}</p>
              </td>
              <td class="tc">
                <p>
                  <el-popconfirm title="确认删除吗?" confirm-button-text="确认" cancel-button-text="取消"
                                 @confirm="delCart(item)">
                    <template #reference>
                      <a href="javascript:;">删除</a>
                    </template>
                  </el-popconfirm>
                </p>
              </td>
            </tr>
          </template>
          <!-- 如果购物车为空，显示空购物车提示 -->
          <tr v-if="cartStore.cartList.length === 0">
            <td colspan="6">
              <div class="cart-none">
                <el-empty description="购物车列表为空">
                  <el-button type="primary" @click="$router.push('/')">随便逛逛</el-button>
                </el-empty>
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <!-- 操作栏 -->
      <div class="action">
        <div class="batch">
          共 {{ cartStore.allCount }} 件商品，已选择 {{ cartStore.selectedCount }} 件，商品合计：
          <span class="red">¥ {{ cartStore.selectedPrice.toFixed(2) }} </span>
        </div>
        <div class="total">
          <el-button size="large" type="primary" @click="handleCheckout">下单结算</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.xtx-cart-page {
  margin-top: 20px;

  .cart {
    background: #fff;
    color: #666;

    table {
      border-spacing: 0;
      border-collapse: collapse;
      line-height: 24px;

      th,
      td {
        padding: 10px;
        border-bottom: 1px solid #f5f5f5;

        &:first-child {
          text-align: left;
          padding-left: 30px;
          color: #999;
        }
      }

      th {
        font-size: 16px;
        font-weight: normal;
        line-height: 50px;
      }
    }
  }

  .seller-row {
    background-color: #f7f7f7;
  }

  .cart-none {
    text-align: center;
    padding: 120px 0;
    background: #fff;

    p {
      color: #999;
      padding: 20px 0;
    }
  }

  .tc {
    text-align: center;

    a {
      color: $xtxColor;
    }

    .xtx-numbox {
      margin: 0 auto;
      width: 120px;
    }
  }

  .red {
    color: $priceColor;
  }

  .green {
    color: $xtxColor;
  }

  .f16 {
    font-size: 16px;
  }

  .goods {
    display: flex;
    align-items: center;

    img {
      width: 100px;
      height: 100px;
    }

    > div {
      width: 280px;
      font-size: 16px;
      padding-left: 10px;

      .attr {
        font-size: 14px;
        color: #999;
      }
    }
  }

  .action {
    display: flex;
    background: #fff;
    margin-top: 20px;
    height: 80px;
    align-items: center;
    font-size: 16px;
    justify-content: space-between;
    padding: 0 30px;

    .xtx-checkbox {
      color: #999;
    }

    .batch {
      a {
        margin-left: 20px;
      }
    }

    .red {
      font-size: 18px;
      margin-right: 20px;
      font-weight: bold;
    }
  }

  .tit {
    color: #666;
    font-size: 16px;
    font-weight: normal;
    line-height: 50px;
  }
}
</style>
